package miiteen.sys.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@ControllerAdvice
public class ControllerError {

    /**
     * 控制器错误捕捉
     */
    @ExceptionHandler(Exception.class)
    public Object exceptionHandler(HttpServletRequest request, Exception e) {
        int status = 500;
        if (e instanceof UnauthorizedException) {
            status = 401;
        } else if (e instanceof NoHandlerFoundException) {
            status = 404;
        } else if (e instanceof MethodArgumentNotValidException) {
            status = 400;
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            List<ObjectError> errors = ex.getBindingResult().getAllErrors();
            String message = errors.get(0).getDefaultMessage();
        }

        String contentType = request.getContentType();
        if (StringUtils.isNotBlank(contentType) && contentType.toLowerCase().contains("json")) {
            ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
            mv.addObject("state", -1 * status);
            mv.addObject("code", "");
            mv.addObject("message", "");
            mv.addObject("data", "");
            return mv;
        } else {
            ModelAndView mv = new ModelAndView();
            switch (status) {
                case 401:
                    mv.setViewName("sys/error/401");
                    break;
                case 404:
                    mv.setViewName("sys/error/404");
                    break;
                case 400:
                    mv.setViewName("sys/error/error");
                    mv.addObject("status", status);
                    mv.addObject("msg", "参数错误");
                    break;
                case 500:
                    mv.setViewName("sys/error/error");
                    mv.addObject("status", status);
                    mv.addObject("msg", "服务器出错");
                    break;

            }
            return mv;
        }
    }
}
